<?php
/**
 * 跨域设置中间键
 * Date: 2025/08/31
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class CrossHttpMiddleware
{
    /**
     * 此中间件用于指定域名来跨域
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 跨域处理
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
        $allowOrigin = explode("||", env("CROSS_URL"));
        if (in_array($origin, $allowOrigin)) {
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: Origin, Content-Type, Cookie, Accept, Authorization');
            header('Access-Control-Expose-Headers: *');
            header('Access-Control-Allow-Methods: *');
            header('Access-Control-Allow-Credentials: true');
        }

        // 如果是 OPTIONS 请求，直接返回响应
        if ($request->isMethod('OPTIONS')) {
            return new Response();
        }
        return $next($request);
    }
}
